import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { HttpClient, HttpEvent, HttpEventType, HttpRequest, HttpResponse, HttpHeaders } from '@angular/common/http';
import { PublicService } from '../public.service';
import { UploadFile, UploadXHRArgs } from 'ng-zorro-antd';
import { Observable, Observer, empty } from 'rxjs';
import { NotificationService, BullySubjectService, ToolsService } from 'app/shared/service';
import { forkJoin } from 'rxjs';
@Component({
    selector: 'itmp-img-upload',
    templateUrl: './img-upload.component.html',
    styleUrls: ['./img-upload.component.css']
})
export class ImgUploadComponent implements OnInit {
    // headers = { 'Content-Type': 'multipart/form-data', 'boundary': '------WebKitFormBoundarykQ3dgw8cHJl4KXY2' };
    imgData = {
        name: null,
        width: null,
        height: null,
        url: null
    };
    @Input() avatarUrl: string; // 默认显示的图片
    @Input() imgUploadUrl: string; // 上传图片的地址
    @Input() isChunkImageUpload = false; // 是否分片上传
    @Input()
    imgFormatLimit = {
        size: 1, // 单位M
        type: ['png', 'jpg', 'jpeg', 'bmp'],
        dimension: [300, 300] // [宽，高]
    };
    init = true;
    loading = false;
    @Output() getImgData = new EventEmitter();
    @Output() getUploadStatus = new EventEmitter();
    @Output() deleteOriginImg = new EventEmitter(); // 删除图片
    constructor(private pub: PublicService, private msg: NotificationService, private http: HttpClient, private tools: ToolsService) {}
    ngOnInit() {}
    // 上传
    beforeUpload = (file: File) => {
        return new Observable((observer: Observer<boolean>) => {
            this.imgData.name = file.name.split('.')[0];
            let isPNG = false;
            this.imgFormatLimit.type.forEach(item => {
                if (file.type.slice(6) === item) {
                    isPNG = true;
                    return;
                }
            });
            if (!isPNG) {
                // this.msg.error('You can only upload JPG file!');
                this.getUploadStatus.emit('type');
                observer.complete();
                return;
            }
            const isLt2M = file.size / 1024 / 1024 < this.imgFormatLimit.size;
            if (!isLt2M) {
                // this.msg.error('Image must smaller than 1MB!');
                this.getUploadStatus.emit('size');
                observer.complete();
                return;
            }
            // check height
            this.checkImageDimension(file).then(dimensionRes => {
                if (!dimensionRes) {
                    // this.msg.error('Image only 300x300 above');
                    this.getUploadStatus.emit('dimension');
                    observer.complete();
                    return;
                }
                observer.next(isPNG && isLt2M && dimensionRes);
                // observer.next(isPNG && isLt2M);
                observer.complete();
            });
        });
    };

    private getBase64(img: File, callback: (img: string) => void): void {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result!.toString()));
        reader.readAsDataURL(img);
    }
    // 图片大小
    private checkImageDimension(file: File): Promise<boolean> {
        return new Promise(resolve => {
            const img = new Image(); // create image
            img.src = window.URL.createObjectURL(file);
            img.onload = () => {
                const width = img.naturalWidth;
                const height = img.naturalHeight;
                this.imgData.width = width;
                this.imgData.height = height;
                window.URL.revokeObjectURL(img.src!);
                if (this.imgFormatLimit.dimension[0] === this.imgFormatLimit.dimension[1]) {
                    resolve(width === height && width <= this.imgFormatLimit.dimension[0]);
                } else {
                    resolve(height <= this.imgFormatLimit.dimension[1] && width <= this.imgFormatLimit.dimension[0]);
                }
            };
        });
    }

    // handleChange(info: { file: UploadFile }): void {
    //     this.avatarUrl = null;
    //     switch (info.file.status) {
    //         case 'uploading':
    //             this.loading = true;
    //             info.file.status = 'done';
    //             break;
    //         case 'done':
    //             // Get this url from response in real world.
    //             if (info.file.thumbUrl) {
    //                 const strBase64 = info.file.thumbUrl.split(',')[1];
    //                 const params = {
    //                     graphicName: this.imgData.name + '.png',
    //                     strBase64
    //                 };
    //                 this.pub.uploadImgByBase64(params).subscribe(res => {
    //                     this.loading = false;
    //                     if (res.data) {
    //                         this.avatarUrl = res.data;
    //                         this.imgData.url = res.data;
    //                         this.getImgData.emit(this.imgData);
    //                     }
    //                 });
    //             } else {
    //                 this.msg.notify({ type: 'warning', path: 'DisseminationManagement.Graphics.Network_error' });
    //             }
    //             // this.getBase64(info.file!.originFileObj!, (img: string) => {
    //             //     this.loading = false;
    //             //     this.avatarUrl = img;
    //             //     this.imgData.url = img;
    //             //     this.getImgData.emit(this.imgData);
    //             // });
    //             break;
    //         // case 'error':
    //         //     // this.msg.error('Network error');
    //         //     this.msg.notify({ type: 'warning', path: 'DisseminationManagement.Graphics.Network_error' });
    //         //     this.loading = false;
    //         //     break;
    //     }
    // }
    customReq = (item: UploadXHRArgs) => {
        const tempImg = this.avatarUrl;
        this.avatarUrl = null;
        this.loading = true;
        // 是否分片上传
        if (this.isChunkImageUpload) {
            this.customBigReq(item, tempImg);
            return;
        }
        const formData = new FormData();
        formData.append('file', item.file as any);
        const xhr = new XMLHttpRequest();
        const that = this;
        // 设置xhr请求的超时时间
        xhr.timeout = 3000;
        // xhr.withCredentials = true;
        xhr.addEventListener('readystatechange', function() {
            if (this.readyState === 4) {
                const res = JSON.parse(this.responseText);
                that.loading = false;
                if (res.data) {
                    that.avatarUrl = res.data;
                    that.imgData.url = res.data;
                    // 判断是否是用户重新上传的图片,并是否继续做替换，若替换就删除之前的
                    if (that.init) {
                        that.init = false;
                    } else {
                        that.deleteOriginImg.emit(tempImg);
                    }
                    that.getImgData.emit(that.imgData);
                } else {
                    that.avatarUrl = tempImg;
                    that.msg.notify({ type: 'warning', path: 'DisseminationManagement.Graphics.Network_error' });
                }
            }
        });
        // 创建一个 post 请求，采用异步
        xhr.open('POST', this.imgUploadUrl, true);
        xhr.send(formData);
        return empty().subscribe();
    };
    deleteImg(event) {
        event.preventDefault();
        event.stopPropagation();
        if (!this.avatarUrl) {
            return;
        } else {
            this.deleteOriginImg.emit(this.avatarUrl);
            this.avatarUrl = '';
        }
    }
    customBigReq = (item: UploadXHRArgs, tempImg) => {
        const nowDate = new Date().getTime();
        const size = item.file.size;
        // const chunkSize = parseInt(size / 10 + '', 10);
        const chunkSize = 512 * 1024;
        const maxChunk = Math.ceil(size / chunkSize);
        let isOver = false;
        const reqs = Array(maxChunk)
            .fill(0)
            .map((_: {}, index: number) => {
                const start = index * chunkSize;
                let end = start + chunkSize;
                if (size - end < 0) {
                    end = size;
                }
                const formData = new FormData();
                formData.append('file', item.file.slice(start, end));
                // 这三个参数暂无作用
                formData.append('start', start.toString());
                formData.append('end', end.toString());
                formData.append('index', index.toString());
                const xhr = new XMLHttpRequest();
                const that = this;
                // xhr.withCredentials = true;
                if (index + 1 === maxChunk) {
                    isOver = true;
                    xhr.addEventListener('readystatechange', function() {
                        if (isOver && index + 1 === maxChunk && this.readyState === 4) {
                            const res = JSON.parse(this.responseText);
                            that.loading = false;
                            if (res.code === '000000') {
                                that.avatarUrl = res.data;
                                that.imgData.url = res.data;
                                that.getImgData.emit(that.imgData);
                                // 判断是否是用户重新上传的图片,并是否继续做替换，若替换就删除之前的
                                if (that.init) {
                                    that.init = false;
                                } else {
                                    that.deleteOriginImg.emit(tempImg);
                                }
                            } else {
                                that.avatarUrl = tempImg;
                                that.msg.notify({ type: 'warning', path: 'DisseminationManagement.Graphics.Network_error' });
                            }
                        }
                    });
                }
                xhr.open('POST', this.imgUploadUrl + `?guid=${nowDate}&chunk=${index + 1}&chunks=${maxChunk}&isOver=${isOver}`);
                xhr.send(formData);
                return empty().subscribe();
            });
        return empty().subscribe();
    };
    // changepic(e) {
    //     var data = new FormData();
    //     var reads = new FileReader();
    //     const img = document.getElementById('imgfile')['files'][0];
    //     data.append("file", img);
    //     var xhr = new XMLHttpRequest();
    //     // xhr.withCredentials = true;
    //     xhr.addEventListener("readystatechange", function () {
    //         if (this.readyState === 4) {
    //         }
    //     });
    //     xhr.open("POST", "http://192.168.0.56:9576/vnqnvmsmgt/uploadImage");
    //     xhr.send(data);
    // }
}
